<template>
  <div class="home-cart-content">
    <!-- 公共头 -->
    <header class="header-fiexed">
      <van-nav-bar title="购物车"
                   left-arrow
                   :right-text="cartList.length > 0 ? (edit ? '完成':'编辑'):''"
                   @click-left="$router.go(-1)"
                   @click-right="edit = !edit" />
    </header>

    <!-- 购物车列表 -->
    <div class="cart-list">

      <van-checkbox-group v-model="selectStore">
        <!-- 每一家店铺的购物车信息 -->
        <div class="store-item"
             v-for="(item,index) in cartList"
             :key="item.store_id">

          <!-- 选中的店铺信息 -->
          <van-checkbox class="checkbox"
                        :name="item.store_id"
                        @click="pickStore(item.store_id,index)">
            <div class="store-info flex align-center">
              <img class="store-icon"
                   src="@/assets/image/order-store.png" />
              <div>{{item.store_name}}</div>
            </div>
          </van-checkbox>

          <!-- 店铺下的商品信息 -->
          <van-checkbox-group v-model="selectGoods[`store_${item.store_id}`]">
            <van-checkbox :name="goodsItem.cart_id"
                          v-for="goodsItem in item.goods"
                          :key="goodsItem.cart_id"
                          class="goods-checkbox checkbox"
                          @click="pickGoods(item.store_id,index)">
              <!-- 商品模块 -->
              <div class="goods-module flex border-bottom"
                   @click.stop="$router.push({name:'GoodsDetail',query:{goods_id:goodsItem.goods_id}})">
                <img class="goods-img"
                     v-lazy="goodsItem.goods_image_url" />

                <!-- 价格，加减 -->
                <div class="goods-info flex-sub">
                  <div class="goods-name ellipsis-2">{{goodsItem.goods_name}}</div>
                  <div class="goods-price flex align-end">
                    <div class="main-price text-price">{{goodsItem.goods_price}}</div>
                    <!-- <div class="del-price">￥{{store_final_total_list.goods_info.goods_marketprice}}</div> -->
                  </div>
                  <!-- 防冒泡触发checkbox事件 -->
                  <div class="goods-num"
                       @click.stop>
                    <van-stepper v-model="goodsItem.goods_num"
                                 integer
                                 :name="goodsItem.cart_id"
                                 @change="updateCount" />
                  </div>
                </div>
              </div>
            </van-checkbox>
          </van-checkbox-group>
        </div>
      </van-checkbox-group>
    </div>

    <!-- 列表为空 -->
    <div class="empty"
         v-show="!cartList || cartList.length <= 0">
      <empty-data :icon="require('@/assets/image/list-empty.png')"
                  empty-desc="亲，购物车没有东西哦！">
        <van-button round
                    class="empty-btn"
                    @click="emptyBtnClick">{{isOnline ? '去首页逛逛':'去登录'}}</van-button>
      </empty-data>
    </div>

    <!-- 订单底部 -->
    <div class="footer"
         v-show="cartList && cartList.length > 0">
      <!--  -->
      <div :class="['fiexed-footer','flex','align-center','content',{'fix-bottom':!$route.meta.footer.show || !showFooter}]">
        <van-checkbox class="checkbox"
                      v-model="all"
                      @click="toggleAll(!all)">
          <div class="label">全选</div>
        </van-checkbox>
        <div class="flex-sub main flex align-baseline justify-end">
          <div class="desc">含运费</div>
          <div>合计：</div>
          <div class="text-price">{{sum}}</div>
        </div>
        <van-button round
                    class="pay-btn"
                    @click="operation">{{edit?'删除':'结算'}}</van-button>
      </div>
    </div>

    <!-- 底部导航 -->
    <!-- <footer class="common-footer-wrap"
            v-if="$route.query.id">
      <div class="foot-list flex">
        <router-link v-for="item in tabList"
                     :key="'tab_'+item.id"
                     :to="{ name: item.path,query:{ id:$route.query.id } }"
                     class="foot-item">
          <div class="icon">
            <img class="unselect"
                 :src="item.icon" />
            <img class="select"
                 :src="item.select_icon" />
          </div>
          <p class="title">{{ item.text }}</p>
        </router-link>
      </div>
    </footer> -->

  </div>
</template>

<script>
import EmptyData from '@/components/EmptyData'
import { cartGet, cartDelete, cartUpdate } from '@/api/homeCart'
import { mapState } from 'vuex'
import { Dialog } from 'vant'
import { _ } from '@/utils/utils'
var addCountWait = null
export default {
  name: 'HomeCart',
  data() {
    return {
      edit: false, // 购物车是否在编辑
      cartList: [], // 购物车列表
      selectStore: [], // 选中的店铺ID
      selectGoods: {}, // 选中的商品ID。用店铺ID做索引
      all: false, // 全选
      sum: 0 // 购物车总价
    }
  },

  components: {
    EmptyData
  },

  props: {
    showFooter: {
      type: Boolean,
      default: true
    }
  },

  computed: mapState({
    isOnline: state => state.user.isOnline
  }),

  created() {
    this.isOnline && this.getCartList()
  },

  methods: {
    /**
     * 缺省图的按钮点击
     */
    emptyBtnClick() {
      if (this.isOnline) {
        this.$router.replace({ name: 'HomeIndex' })
      } else {
        this.$router.push({ name: 'HomeLogin' })
      }
    },
    /**
     * 获取订单列表
     * @param {Boolean} select 是否进来就全选列表
     */
    getCartList(select = true) {
      cartGet().then(res => {
        if (res && res.result.cart_val.length > 0) {
          this.cartList = Object.assign([], res.result.cart_val)
          this.sum = res.result.sum
          select && this.toggleAll(true)
          !select && this.getPrice()
        } else {
          this.cartList = []
          this.sum = 0
          this.selectGoods = {}
          this.selectStore = []
          this.all = false
        }
      })
    },

    /**
     * 全选/全不选
     * @param {Boolean} state true为全选  false为取消全选
     */
    toggleAll(state) {
      if (state) {
        var storeId = []
        var goodsId = {}
        var sum = 0
        // 获取店铺ID
        _.each(this.cartList, store => {
          storeId.push(store.store_id)
          goodsId[`store_${store.store_id}`] = []
          // 获取商品ID
          _.each(store.goods, goods => {
            goodsId[`store_${store.store_id}`].push(goods.cart_id)
            sum += goods.goods_num * goods.goods_price
          })
        })
        this.all = true
        this.selectStore = storeId
        this.selectGoods = goodsId
        this.sum = sum.toFixed(2)
      } else {
        this.all = false
        this.selectGoods = {}
        this.selectStore = []
        this.sum = 0
      }
    },

    /**
     * 选中商品/取消商品
     * @param {Number} storeId 关联的店铺ID
     * @param {Number} index 所在列表的index
     */
    pickGoods(storeId, index) {
      // 这里因为checkbox用的是@click事件，不是@change事件。会有延迟，所以必须用setTimeOut
      // 如果改用@change事件，3个地方联动会互相影响（全选，商品，店铺）
      setTimeout(() => {
        var selLength = this.selectGoods[`store_${storeId}`].length
        if (selLength === this.cartList[index].goods.length) {
          this.selectStore.push(storeId)
          this.all = this.selectStore.length === this.cartList.length
        } else {
          this.selectStore = _.without(storeId)
          this.all = false
        }
        this.getPrice()
      }, 100)
    },
    /**
     * 选中商品/取消商品
     * @param {Number} storeId 关联的店铺ID
     * @param {Number} index 所在列表的index
     */
    pickStore(storeId, index) {
      // 这里因为checkbox用的是@click事件，不是@change事件。会有延迟，所以必须用setTimeOut
      // 如果改用@change事件，3个地方联动会互相影响（全选，商品，店铺）
      setTimeout(() => {
        this.all = this.selectStore.length === this.cartList.length
        if (this.selectStore.indexOf(storeId) !== -1) {
          // 刚选中该店铺
          this.selectGoods[`store_${storeId}`] = this.cartList[index].goods.map(
            goods => goods.cart_id
          )
        } else {
          // 取消选中该店铺
          this.selectGoods[`store_${storeId}`] = []
        }
        this.getPrice()
      }, 100)
    },

    /**
     * 更新购物车数量
     * 参数看vant文档
     * value 就是最新的数量
     * detail绑定了商品的cart_id
     */
    updateCount(value, detail) {
      clearTimeout(addCountWait)
      // 防抖函数
      addCountWait = setTimeout(() => {
        cartUpdate(detail.name, value)
          .then(res => {
            this.$toast({
              message: res.message || '操作成功',
              type: 'success'
            })
            this.getPrice()
          })
          .catch(res => {
            if (res.message !== '操作失败') {
              this.getCartList(false) // 更新订单列表。不更新选中状态
              this.$toast({
                message: res.message,
                type: 'fail'
              })
            }
          })
      }, 200)
    },

    /**
     * 计算总价
     */
    getPrice() {
      var goodsList = []
      // 获取选中的商品ID
      _.each(this.selectGoods, item => {
        goodsList.push(...item)
      })

      if (goodsList.length === 0) {
        this.sum = 0
      } else {
        var sum = 0
        _.each(this.cartList, store => {
          _.each(store.goods, goods => {
            if (goodsList.indexOf(goods.cart_id) !== -1) {
              sum += goods.goods_num * goods.goods_price
            }
          })
        })
        this.sum = sum.toFixed(2)
      }
    },

    /**
     * 删除 / 结算订单
     */
    operation() {
      var goodsList = []
      // 获取选中的商品ID
      _.each(this.selectGoods, item => {
        goodsList.push(...item)
      })
      if (goodsList.length === 0) {
        this.$toast({
          type: 'loading',
          message: `请选择需要${this.edit ? '删除' : '结算'}的商品`
        })
        return false
      }

      if (this.edit) {
        Dialog.confirm({
          message: '确定删除选中的商品吗？',
          confirmButtonColor: '#e9533e'
        })
          .then(() => {
            // 删除商品
            cartDelete(goodsList.join(','))
              .then(res => {
                this.$toast({
                  type: 'success',
                  message: res.message || '操作成功'
                })
                this.getCartList(true) // 更新列表，全选
              })
              .catch(res => {
                this.$toast({
                  type: 'fail',
                  message: res.message
                })
              })
          })
          .catch(() => {
            // on cancel
          })
      } else {
        // 结算商品
        var goodsQuery = [] // 下单的参数，商品id|数量,商品ID|数量
        _.each(this.cartList, store => {
          _.each(store.goods, goods => {
            if (goodsList.indexOf(goods.cart_id) !== -1) {
              goodsQuery.push(goods.cart_id + '|' + goods.goods_num)
            }
          })
        })

        this.$router.push({
          name: 'MakeOrder',
          query: { cart_id: goodsQuery.join(',') }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.home-cart-content {
  font-size: 16px;

  /deep/ .van-nav-bar__text {
    color: #666666;
  }

  // 购物车列表
  .cart-list {
    padding: 10px;

    .store-item {
      padding: 0 10px;
      background-color: #ffffff;
      border-radius: 10px;
      & + .store-item {
        margin-top: 10px;
      }
      // 店铺信息
      .store-info {
        color: #333333;
        font-size: 15px;
        height: 60px;
        .store-icon {
          width: 20px;
          height: 20px;
          margin-right: 8px;
        }
      }

      // 商品信息
      .goods-checkbox {
        /deep/ .van-checkbox__label {
          flex: 1;
        }
      }
      .goods-checkbox + .goods-checkbox {
        position: relative;
        &::after {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 1px;
          background-color: #eeeeee;
          content: '';
          transform: scaleY(0.5);
        }
      }
      .goods-module {
        padding: 15px 0;
        width: 100%;
        .goods-img {
          width: 95px;
          height: 95px;
          border-radius: 5px;
          margin-right: 12px;
        }

        .goods-info {
          padding: 5px 0;
          justify-content: space-between;
          display: flex;
          flex-direction: column;
          position: relative;

          .goods-price {
            margin-top: 15px;
          }

          .main-price {
            color: $mainColor;
            font-weight: bold;
            margin-right: 5px;
            font-size: 14px;
          }

          .del-price {
            text-decoration: line-through;
            color: #666666;
            font-size: 11px;
          }

          .goods-num {
            position: absolute;
            bottom: 0px;
            right: 0px;
          }
        }
      }
    }
  }

  // 订单底部
  .footer {
    width: 100%;
    height: 50px;
    .fiexed-footer {
      position: fixed;
      bottom: 50px;
      left: 0;
      height: 50px;
      width: 100%;
      background-color: #ffffff;
      z-index: 100;
      padding: 0 15px;
      color: #666666;
      font-size: 12px;

      &.fix-bottom {
        bottom: 0;
      }
      .label {
        line-height: 50px;
      }
      .content {
        height: 50px;
      }
      .main {
        margin-right: 25px;
        color: #333333;
        font-size: 16px;
        .desc {
          color: #999999;
          font-size: 10px;
          margin-right: 10px;
        }
        .text-price {
          color: $mainColor;
        }
      }

      /deep/ .van-checkbox__label {
        flex: 1;
        height: 50px;
      }

      .pay-btn {
        background-color: $mainColor;
        color: #ffffff;
        width: 90px;
        height: 37px;
        line-height: 37px;
      }
    }
  }

  // 列表为空
  .empty {
    width: 100%;
    height: 70vh;
    .empty-btn {
      background-color: transparent;
      width: 150px;
      height: 40px;
      line-height: 40px;
      border-color: $mainColor;
      color: $mainColor;
      font-size: 15px;
    }
  }
}
</style>
